<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, View, Delete } from '@element-plus/icons-vue'
import { getTravelPlanList, getTravelPlanDetail, deleteTravelPlan } from '@/api/travelPlan'
import { getUserDetail } from '@/api/user'

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)

// 查询参数
const queryParams = ref({
  page: 1,
  pageSize: 10,
  keyword: '' // 搜索关键词（标题、城市）
})

// 详情对话框
const detailDialogVisible = ref(false)
const currentPlan = ref(null)
const detailLoading = ref(false)

// 加载旅行计划列表
const loadTravelPlanList = async () => {
  loading.value = true
  try {
    // 实际API调用
    const result = await getTravelPlanList(queryParams.value)
    console.log('API返回数据:', result)
    
    if (result.success && Array.isArray(result.data)) {
      tableData.value = await attachAuthorInfo(result.data)
      total.value = result.data.length
    } else {
      // 返回结构不符合预期或失败时，清空并提示错误
      tableData.value = []
      total.value = 0
      ElMessage.error(result.message || '旅行计划列表加载失败')
    }
  } catch (error) {
    console.error('加载旅行计划列表失败:', error)
    // 如果API调用出错，清空并提示错误
    tableData.value = []
    total.value = 0
    ElMessage.error('旅行计划列表加载失败，请稍后重试')
  } finally {
    loading.value = false
  }
}


// 搜索
const handleSearch = () => {
  queryParams.value.page = 1
  loadTravelPlanList()
}

// 重置搜索
const handleReset = () => {
  queryParams.value = {
    page: 1,
    pageSize: 10,
    keyword: ''
  }
  loadTravelPlanList()
}

// 分页变化
const handlePageChange = (page) => {
  queryParams.value.page = page
  loadTravelPlanList()
}

const handleSizeChange = (size) => {
  queryParams.value.pageSize = size
  queryParams.value.page = 1
  loadTravelPlanList()
}

// 查看详情
const handleViewDetail = async (row) => {
  detailLoading.value = true
  currentPlan.value = row
  
  try {
    // 尝试获取详细信息
    const result = await getTravelPlanDetail(row.id)
    if (result.success) {
      currentPlan.value = result.data
    }
    // 详情补充作者信息
    if (!currentPlan.value.author && currentPlan.value.userId) {
      try {
        const u = await getUserDetail(currentPlan.value.userId)
        if (u.success && u.data) {
          currentPlan.value.author = {
            id: u.data.id,
            username: u.data.username,
            nickname: u.data.nickname,
            avatar: u.data.avatar
          }
        }
      } catch (_) {}
    }
    // 直接使用后端 dailyPlans 结构
    currentPlan.value.dailyPlansNormalized = Array.isArray(currentPlan.value?.dailyPlans)
      ? currentPlan.value.dailyPlans
      : []
  } catch (error) {
    console.error('获取旅行计划详情失败:', error)
    // 使用行数据作为详情（直接使用 dailyPlans）
    currentPlan.value.dailyPlansNormalized = Array.isArray(currentPlan.value?.dailyPlans)
      ? currentPlan.value.dailyPlans
      : []
  } finally {
    detailLoading.value = false
    detailDialogVisible.value = true
  }
}

// 删除旅行计划
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除旅行计划"${row.title}"吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )

    const result = await deleteTravelPlan(row.id)
    if (result.success) {
      ElMessage.success('删除成功')
      loadTravelPlanList()
    } else {
      ElMessage.error(result.message || '删除失败')
      loadTravelPlanList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除旅行计划失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 截取文本
const truncateText = (text, length = 50) => {
  if (!text) return '-'
  return text.length > length ? text.substring(0, length) + '...' : text
}

// 为列表项补充作者信息
const attachAuthorInfo = async (list) => {
  const ids = [...new Set(list.map(i => i.userId).filter(Boolean))]
  const map = {}
  await Promise.all(ids.map(async id => {
    try {
      const res = await getUserDetail(id)
      if (res.success && res.data) {
        map[id] = res.data
      }
    } catch (_) {}
  }))
  return list.map(item => ({
    ...item,
    author: map[item.userId]
      ? {
          id: map[item.userId].id,
          username: map[item.userId].username,
          nickname: map[item.userId].nickname,
          avatar: map[item.userId].avatar
        }
      : item.author
  }))
}

// 审核状态与可见性展示辅助
const getStatusType = (status) => {
  switch (status) {
    case 'approved':
      return 'success'
    case 'rejected':
      return 'danger'
    case 'pending':
      return 'warning'
    default:
      return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 'approved':
      return '已通过'
    case 'rejected':
      return '已拒绝'
    case 'pending':
      return '待审核'
    case 'draft':
      return '草稿'
    default:
      return status || '-'
  }
}

const getVisibilityText = (isPublic) => (isPublic ? '公开' : '私密')

// 已移除规范化函数，直接使用后端 dailyPlans/locations

onMounted(() => {
  loadTravelPlanList()
})
</script>

<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div class="filter-item">
        <el-input
          v-model="queryParams.keyword"
          placeholder="输入关键词搜索"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon class="el-input__icon"><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
        <el-button :icon="Refresh" @click="handleReset">重置</el-button>
      </div>
    </el-card>

    <el-card class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="200">
          <template #default="scope">
            <el-link type="primary" @click="handleViewDetail(scope.row)">
              {{ scope.row.title }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="cityName" label="城市" width="120" />
        <el-table-column label="作者" width="170">
          <template #default="{ row }">
            <div style="display: flex; align-items: center; gap: 8px">
              <el-avatar :size="32" :src="row.author?.avatar" style="flex-shrink: 0">
                <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
              </el-avatar>
              <div style="flex: 1; min-width: 0; overflow: hidden">
                <div style="font-size: 13px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                  {{ row.author?.nickname || row.author?.username || '-' }}
                </div>
                <div style="color: #999; font-size: 11px">ID: {{ row.userId || '-' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="days" label="天数" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isPublic" label="可见性" width="90">
          <template #default="{ row }">
            <el-tag :type="row.isPublic ? 'success' : 'info'" size="small">
              {{ getVisibilityText(row.isPublic) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_at || scope.row.createdAt || scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              :icon="View"
              circle
              @click="handleViewDetail(scope.row)"
              title="查看详情"
            />
            <el-button
              type="danger"
              :icon="Delete"
              circle
              @click="handleDelete(scope.row)"
              title="删除"
            />
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          :current-page="queryParams.page"
          :page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="旅行计划详情"
      width="800px"
      destroy-on-close
    >
      <div v-if="currentPlan" class="detail-container">
        <div class="detail-header">
          <h2>{{ currentPlan.title }}</h2>
          <div class="detail-author" v-if="currentPlan.userId">
            <el-avatar :size="30" :src="currentPlan.author?.avatar">
              <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
            </el-avatar>
            <span style="margin-left: 8px">
              {{ currentPlan.author?.nickname || currentPlan.author?.username || '-' }}
              (ID: {{ currentPlan.userId }})
            </span>
          </div>
          <div class="detail-meta">
            <span>城市：{{ currentPlan.cityName }}</span>
            <span>天数：{{ currentPlan.days }} 天</span>
            <span>创建时间：{{ formatDate(currentPlan.created_at || currentPlan.createdAt || currentPlan.createTime) }}</span>
            <span>
              状态：
              <el-tag :type="getStatusType(currentPlan.status)" size="small">
                {{ getStatusText(currentPlan.status) }}
              </el-tag>
            </span>
            <span>
              可见性：
              <el-tag :type="currentPlan.isPublic ? 'success' : 'info'" size="small">
                {{ getVisibilityText(currentPlan.isPublic) }}
              </el-tag>
            </span>
          </div>
        </div>
        
        <el-divider />
        
        <div class="detail-section">
          <h3>行程安排</h3>
          <div v-if="currentPlan && currentPlan.dailyPlansNormalized && currentPlan.dailyPlansNormalized.length > 0">
            <div v-for="(day, index) in currentPlan.dailyPlansNormalized" :key="index" class="day-item">
              <h4>第 {{ day.day }} 天</h4>
              <el-timeline>
                <el-timeline-item
                  v-for="(loc, itemIndex) in (Array.isArray(day.locations) ? day.locations : [])"
                  :key="itemIndex"
                  :timestamp="loc.time || ''"
                  placement="top"
                >
                  <div class="timeline-item">
                    <div class="timeline-title">{{ loc.name }}</div>
                    <div class="timeline-location">{{ loc.note }}</div>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>
          </div>
          <el-empty v-else description="暂无行程安排" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.filter-item .el-input {
  width: 240px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-container {
  padding: 0 20px;
}

.detail-header {
  text-align: center;
  margin-bottom: 20px;
}

.detail-meta {
  display: flex;
  justify-content: center;
  gap: 20px;
  color: #666;
  margin-top: 10px;
}

.detail-section {
  margin-bottom: 30px;
}

.day-item {
  margin-bottom: 30px;
}

.timeline-item {
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.timeline-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.timeline-location {
  color: #666;
  font-size: 14px;
}
</style>